// index.ts
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { Button, message, Space } from 'antd';
import useUserStore from '../store/useUserStore';

type Result<T> = {
  code: number;
  message: string;
  result: T;
};

// 导出Request类，可以用来自定义传递配置来创建实例
export class Request {
  // axios 实例
  instance: AxiosInstance;
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = { baseURL: 'http://192.168.2.69:9000/api', timeout: 60000 };

  constructor(config: InternalAxiosRequestConfig) {
    // 使用axios.create创建axios实例
    this.instance = axios.create(Object.assign(this.baseConfig, config));

    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 一般会请求拦截里面加token，用于后端的验证
        const token = localStorage.getItem('useUserStore') as string;
        if (token) {
          config.headers!.Authorization = `Bearer ${JSON.parse(token).state.token}`;
        }

        return config;
      },
      (err: any) => {
        // 请求错误，这里可以用全局提示框进行提示
        return Promise.reject(err);
      }
    );

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        // 系统如果有自定义code也可以在这里处理
        if (res.status === 201 && !res.data.success) {
          message.warning(res.data.message);
        } else {
          return res.data;
        }
      },
      (err: any) => {
        console.log(err, 'request');
        // 这里用来处理http常见错误，进行全局提示
        let msg = '';
        if (err.response.status.toString().startsWith('4')) {
          msg = err.response.data.data;
          if (err.response.data.code === 10000) {
            message.warning('登录有效期过期');
            const { outLogin } = useUserStore.getState();
            outLogin();
            window.location.href = '/login';
          }
        } else if (err.response.status.toString().startsWith('5')) {
          msg = err.response.data.data;
        } else {
          window.location.href = '/login';
        }
        return Promise.reject(err.response);
      }
    );
  }

  // 定义请求方法
  public request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<Result<T>>> {
    return this.instance.request(config);
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<Result<T>>> {
    return this.instance.get(url, config);
  }

  public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<Result<T>>> {
    return this.instance.post(url, data, config);
  }

  public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<Result<T>>> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<Result<T>>> {
    return this.instance.delete(url, config);
  }
}

// 默认导出Request实例
export default new Request({});
